import store from '@/config/store';
import $http from '@/config/requestConfig'
import { apis } from '@/api'
import base from '@/config/base';

let code = "";
let openid = "";
let loginStart = false;

// 登录（所有端）
function login(){
	if (loginStart) {
		return Promise.reject('登录已经开始');
	}
	loginStart = true;
	// #ifdef MP-WEIXIN
	console.log('openid', openid)
	wxLogin();
	// #endif
	// #ifdef H5
	if (store.state.env === 'wxh5') {
		wxh5Login();
	} else {
		h5Login();
	}
	// #endif
}

function resetLoginStart() {
	loginStart = false;
}

function h5Login() {
	uni.showToast({
		title: '请先登录',
		icon: 'none',
		duration: 2000
	})
	setTimeout(function() {
		uni.navigateTo({
			url: '/pages/user/login/login'
		})
	}, 2000)
}

function wxh5Login() {
	// 判断是否有code
	const exp = /code=([0-9a-zA-Z]+)&/g
	let code = exp.exec(location.href)
	if (code) {
		code = code[1]
		apis.wechat.wxLogin({
			code,
			mode: 'gzh'
		}).then(res => {
			if (!res) {
				return false
			}
			store.commit('user/setAuthorization', res.authorization);
			store.commit('user/setCookie', res.cookie);
			return store.dispatch('user/getUserInfo');
		}).then(res => {
			if (res) {
				location.search = '';
				if (store.state.path) {
					let url = store.state.path
					if (store.state.query) {
						let params = store.state.query
						let paramString = Object.keys(params).map(key => key+'='+params[key]).join('&')
						url += (url.indexOf('?') > -1 ? '&' : '?') + paramString
					}
					uni.reLaunch(url)
				} else {
					uni.reLaunch('pages/home/home/home')
				}
			}
		});
	} else {
		let url = base.redirectUrl
		console.log(store.state.path)
		if (store.state.path) {
			url += '/#/' + store.state.path
			if (store.state.query) {
				let params = store.state.query
				let paramString = Object.keys(params).map(key => key+'='+params[key]).join('&')
				url += (url.indexOf('?') > -1 ? '&' : '?') + paramString
			}
		}
		const reUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + base.gzhAppid +
		    '&redirect_uri=' + encodeURIComponent(url) +
		    '&response_type=code&scope=snsapi_userinfo&state=login#wechat_redirect'
		console.log(url, reUrl)
		location.replace(reUrl)
	}
}

// 微信小程序登录
function wxLogin() {
	// 判断是否已经开始登录
	if (openid) {
		return;
	}
	uni.login({
		provider: 'weixin',
		success(loginRes) {
			if (loginRes.errMsg == 'login:ok') {
				code = loginRes.code;
				// 通过code获取用户信息，如果获取到了openid，则是未注册用户
				apis.wechat.wxLogin({ code, mode: 'xcx' })
					.then(res => {
						if (res.openid) {
							openid = res.openid;
							uni.navigateTo({
								url: '/pages/user/mp-login/mp-login?type=register'
							})
						} else {
							store.commit('user/setAuthorization', res.authorization);
							store.commit('user/setCookie', res.cookie);
							if (store.path) {
								uni.reLaunch(store.path);
							} else {
								uni.reLaunch('pages/circle/circle/circle');
							}
						}
					})
					.catch(err => {
						// loginStart = false;
					})
			}
		}
	});
}

//微信小程序获取用户信息
function getPhoneNumber(info, callback) {
	const httpData = {
		mode: 'xcx',
		openid: openid, // 用户openid
		iv: info.iv,    //小程序加密算法的初始向量
		encrypted_data: info.encryptedData //包括敏感数据在内的完整用户信息的加密数据
	};
	// 绑定手机号，此时用户已经注册成功了
	apis.wechat.bindPhone({ 
		openid: openid,
		iv: info.iv,
		encrypted_data: info.encryptedData
	})
		.then(res => {
			store.commit('user/setAuthorization', res.authorization);
			store.commit('user/setCookie', res.cookie);
			callback && callback();
		}, err => {
			loginStart = false;
		});
}

//微信小程序获取用户信息
function getUserInfo(info, callback) {
	const httpData = {
		nickname: info.nickName,
		avatar_url: info.avatarUrl,
		wx_city: info.city
	};
	// 更新用户信息
	apis.user.update(httpData)
		.then(res => {
			loginStart = false;
			callback && callback();
		}, err => {
			loginStart = false;
		});
}


export {
	login,
	wxLogin,
	getPhoneNumber,
	getUserInfo,
	resetLoginStart
}